//
//  UIColor+Extension.swift
//  CommonTool
//
//  Created by tenroadshow on 12.1.22.
//

import Foundation
import UIKit


public extension UIImage {
    
    convenience init?(color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) {
        UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
        defer {
            UIGraphicsEndImageContext()
        }
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(CGRect(origin: CGPoint.zero, size: size))
        context?.setShouldAntialias(true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        guard let cgImage = image?.cgImage else {
            self.init()
            return nil
        }
        self.init(cgImage: cgImage)
    }
    
    /// 质量压缩
    func compress(maxSize: Int) -> Data? {
        var compression: CGFloat = 1
        guard var data = self.jpegData(compressionQuality: 1) else { return nil }
        if data.count < maxSize {
            return data
        }
        var max: CGFloat = 1
        var min: CGFloat = 0
        for _ in 0..<6 {
            compression = (max + min) / 2
            data = self.jpegData(compressionQuality: compression)!
            if CGFloat(data.count) < CGFloat(maxSize){
                min = compression
            } else if data.count > maxSize {
                max = compression
            } else {
                break
            }
        }
        return data
    }
    
    /// 尺寸压缩
    func compress(maxLength: CGFloat) -> UIImage? {
        if maxLength <= 0 { return self }
        
        var imgMax:CGFloat = 0
        if self.size.width/self.size.height >= 1{
            imgMax = self.size.width
        }else{
            imgMax = self.size.height
        }
        if imgMax > maxLength {
            let ratio = maxLength/imgMax
            let newW  = self.size.width * ratio
            let newH  = self.size.height * ratio
            
            let newSize = CGSize(width: newW, height: newH)
            UIGraphicsBeginImageContext(newSize)
            self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            guard let _img = img else { return  nil}
            return _img
        }else{
            return self
        }
    }
    
    func resizableImage() -> UIImage {
        return resizableImage(withCapInsets: UIEdgeInsets(top: size.height * 0.5,
                                                          left: size.width * 0.5,
                                                          bottom: size.height * 0.5,
                                                          right: size.width * 0.5),
                              resizingMode: .stretch)
    }
    
    /// 创建二维码
    static func createQRCodeImage(content: String,
                                  logoImage: UIImage? = nil,
                                  qrSize: CGSize? = nil,
                                  logoSize: CGSize? = nil) -> UIImage? {
        guard let contentData = content.data(using: .utf8) else { return nil }
        guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else {
            return nil
        }
        qrFilter.setDefaults()
        qrFilter.setValue(contentData, forKey: "inputMessage")
        qrFilter.setValue("H", forKey: "inputCorrectionLevel")
        guard let ciImage = qrFilter.outputImage else { return nil }
        
        let qrImage = UIImage(ciImage: ciImage)
        
        guard let logo = logoImage, let bigSize = qrSize, let smallSize = logoSize else { return qrImage }
        let xy = abs((bigSize.width - smallSize.width) / 2.0)
        return fillImage(inputImage: qrImage,
                         fillImage: logo,
                         inputRect: CGRect(origin: .zero, size: bigSize),
                         fillRect: CGRect(origin: CGPoint(x: xy, y: xy), size: smallSize))
    }
    
    /// 合成图片
    static func fillImage(inputImage: UIImage?,
                          fillImage: UIImage?,
                          inputRect: CGRect,
                          fillRect: CGRect) -> UIImage? {
        guard let input = inputImage, let fill = fillImage else { return inputImage }
        UIGraphicsBeginImageContextWithOptions(inputRect.size, true, UIScreen.main.scale)
        input.draw(in: inputRect)
        fill.draw(in: fillRect)
        guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext()
            return inputImage
        }
        UIGraphicsEndImageContext()
        return newImage
    }

    /// 生成渐变图片
    static func gradientImage(colors: [UIColor], size: CGSize) -> UIImage? {
        if colors.isEmpty || size.width <= 0 || size.height <= 0 {
            return nil
        }
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(origin: .zero, size: size)
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.colors = colors.map { $0.cgColor }
        
        UIGraphicsBeginImageContextWithOptions(size, gradientLayer.isOpaque, UIScreen.main.scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        gradientLayer.render(in: context)
        let outputImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return outputImage
    }

}
